<template>
	<view class="page-top-bg"></view>
	<AdaptiveNavBar :showBack="true" title="申请记录" :showHome="false" :showShadow="false" text-color="#ffffff" background-color="#57BE9C" />
	<view class="content-area" :style="{ marginTop: navbarTotalHeightRpx }">
		<view class="application-record-container">
			<!-- 产品信息展示区 -->
			<view class="main-top-period" :style="{ marginTop: navbarTotalHeightRpx }">
				<view class="product-card-wrapper">
					<ProductCard :info="productCardInfo" />
				</view>
			</view>

			<!-- 筛选和搜索区 -->
			<section class="section">
				<view class="section-header">
					<view class="section-header__left">
						<FontIcon name="icon-xuanzebanqi" class="section-header__icon"></FontIcon>
						<view class="section-header__title">筛选条件</view>
					</view>
				</view>
				<view class="filter-content">
					<view class="filter-row">
						<picker style="flex:1" @change="onOperationTypeChange" :value="operationTypeIndex" :range="operationTypes">
							<view class="picker-item">
								<text class="picker-text">{{ operationTypes[operationTypeIndex] }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
						<view class="search-input-wrapper">
							<input class="search-input" placeholder="请输入关键词搜索" v-model="searchKeyword" @input="onSearchInput" />
							<FontIcon name="icon-sousuo" class="search-icon"></FontIcon>
						</view>
					</view>
					<view class="date-row">
						<picker style="flex:1" mode="date" @change="onStartDateChange" :value="startDate">
							<view class="date-picker">
								<text class="date-text">{{ startDate || '开始日期' }}</text>
								<text class="date-arrow">▼</text>
							</view>
						</picker>
						<picker style="flex:1" mode="date" @change="onEndDateChange" :value="endDate">
							<view class="date-picker">
								<text class="date-text">{{ endDate || '结束日期' }}</text>
								<text class="date-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>
			</section>

			<!-- 申请记录列表 -->
			<section class="section">
				<view class="section-header">
					<view class="section-header__left">
						<FontIcon name="icon-xuanzebanqi" class="section-header__icon"></FontIcon>
						<view class="section-header__title">申请记录</view>
					</view>
				</view>
				<view class="application-list" v-if="filteredApplications.length > 0">
					<view class="application-card" v-for="(application, index) in filteredApplications" :key="index" @click="viewApplicationDetail(application)">
						<view class="card-header">
							<view class="agency-info">
								<view class="group-badge">组团</view>
								<text class="agency-name">{{ application.agencyName }}</text>
								<text class="play-icon">▶</text>
							</view>
							<view class="rating">
								<text class="star-icon">★</text>
								<text class="rating-value">{{ application.rating }}</text>
							</view>
						</view>
						<view class="card-detail-row">
							<text class="detail-label">客源城市</text>
							<text class="detail-value">{{ application.sourceCity }}</text>
						</view>
						<view class="card-detail-row">
							<text class="detail-label">申请名额</text>
							<text class="detail-value">{{ application.quota }}</text>
						</view>
						<view class="card-footer">
							<view class="time-info">
								<text class="time-label">{{ application.applyTime }}</text>
								<text class="status" :class="application.statusClass">{{ application.status }}</text>
							</view>
							<view class="operator-info">
								<text class="operator-label">操作员</text>
								<text class="operator-name">{{ application.operator }}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="empty-state" v-else>
					<text class="empty-text">暂无申请记录</text>
				</view>
			</section>

		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-action-bar">
			<view class="action-button" @click="goBack">
				<text class="button-text">返回</text>
			</view>
		</view>
	</view>
</template>

<script>
import { request } from '@/utils/request.js'
import ProductCard from '@/components/ProductCard.vue'
import AdaptiveNavBar from '@/components/AdaptiveNavBar.vue'

export default {
	components: {
		ProductCard,
		AdaptiveNavBar
	},
	data() {
		return {
			productId: null,
			// 产品信息
			productInfo: {
				title: '亲近自然-捕捞采摘|研学商品服务基础模块首缩略图两...',
				image: '/static/6.jpg',
				ageRange: '6-10岁',
				duration: '2日',
				location: '河南新乡',
				tag: '新乡接待',
				price: '渠道¥600.00'
			},
			// 筛选条件
			operationTypes: ['请选择操作类型', '同意', '驳回', '待处理'],
			operationTypeIndex: 0,
			searchKeyword: '',
			startDate: '',
			endDate: '',
			// 申请记录数据
			applications: [],
			filteredApplications: []
		}
	},
	
	computed: {
		// 导航栏总高度（rpx）
		navbarTotalHeightRpx() {
			return this.$navbarUtil ? this.$navbarUtil.getNavbarTotalHeightRpx() : '88rpx'
		},
		// 转换 productInfo 为 ProductCard 组件需要的格式
		productCardInfo() {
			return {
				mainImage: this.productInfo.image,
				mainInfo: {
					productSpu: {
						name: this.productInfo.title,
						mainImage: this.productInfo.image
					},
					productSku: {
						title: this.productInfo.title,
						minYearOld: this.productInfo.ageRange?.split('-')[0] || '',
						maxYearOld: this.productInfo.ageRange?.split('-')[1]?.replace('岁', '') || '',
					},
					price: this.productInfo.price?.replace('¥', '') || '0',
					saleArea: this.productInfo.tag || ''
				},
				mergedItineraries: this.productInfo.duration ? 
					[{ details: [{ items: [{ address: this.productInfo.location || '' }] }] }] : [],
				ChannelName: this.productInfo.tag || ''
			}
		}
	},
	
	onLoad(options) {
		// 获取产品ID
		if (options.productId) {
			this.productId = options.productId
			this.loadProductInfo()
			this.loadApplicationRecords()
		}
	},

methods: {
		goBack() {
			uni.navigateBack()
		},
		
		// 加载产品信息
		async loadProductInfo() {
			try {
				const companyInfo = uni.getStorageSync('companyInfo') || {}
				const res = await request({
					url: `/product-spu/getProduct?id=${this.productId}&merchantType=${companyInfo.businessType || ''}`,
					method: 'GET'
				})
				
				if (res && (res.code === 200 || res.code === 1) && res.data) {
					const d = res.data
					const p1 = d.p1 || {}
					const productSpu = p1.productSpu || d.productSpu || d.mainInfo?.productSpu || {}
					const productSku = p1.productSku || d.productSku || d.mainInfo?.productSku || {}
					
					// 处理图片
					let firstImg = '/static/6.jpg'
					if (Array.isArray(productSku.images) && productSku.images.length > 0) {
						const img0 = productSku.images[0]
						firstImg = (typeof img0 === 'string') ? img0 : (img0.url || img0.imgUrl || productSpu.mainImage || '/static/6.jpg')
					} else if (productSpu.mainImage) {
						firstImg = productSpu.mainImage
					}
					
					// 处理年龄范围
					const ageRange = (productSku.minYearOld != null && productSku.maxYearOld != null)
						? `${productSku.minYearOld}-${productSku.maxYearOld}岁`
						: (productSku.ageRange || productSku.fitAge || '6-10岁')
					
					// 处理时长
					const duration = productSku.duration || productSku.days || '2日'
					
					// 处理地点
					const location = productSpu.cityName || productSpu.address || productSpu.city || '河南新乡'
					
					// 处理价格
					const price = (productSku.channelPrice != null)
						? `渠道¥${Number(productSku.channelPrice).toFixed(2)}`
						: (productSpu.price != null)
							? `渠道¥${Number(productSpu.price).toFixed(2)}`
							: '渠道¥600.00'
					
					this.productInfo = {
						title: productSku.title || productSpu.name || this.productInfo.title,
						image: firstImg,
						ageRange,
						duration,
						location,
						tag: productSpu.tag || '新乡接待',
						price
					}
				}
			} catch (error) {
				console.error('加载产品信息失败:', error)
			}
		},
		
		// 加载申请记录
		async loadApplicationRecords() {
			try {
				const res = await request({
					url: `/call-apply/list/spu?spuId=${this.productId}`,
					method: 'GET'
				})
				
				if (res && res.code === 200) {
					this.applications = res.data.map(item => ({
						id: item.id,
						relationId: item.relationId,
						agencyName: item.merchantDTO?.name || '未知机构',
						rating: '4.8',
						sourceCity: item.merchantDTO?.address || '未知城市',
						quota: `${item.applyQuota || 0}人 * ${item.groupCount || 0}团`,
						applyTime: this.formatDate(item.createdAt),
						status: item.status,
						statusClass: this.getStatusClass(item.status),
						operator: '李乐峰', // 默认操作员，实际应该从接口获取
						reply: item.reply || '',
						merchantInfo: item.merchantDTO
					}))
					
					this.filteredApplications = [...this.applications]
				}
			} catch (error) {
				console.error('加载申请记录失败:', error)
			}
		},
		
		// 格式化日期
		formatDate(dateString) {
			if (!dateString) return ''
			const date = new Date(dateString)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			const seconds = String(date.getSeconds()).padStart(2, '0')
			return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			switch (status) {
				case '同意':
				case '已同意':
					return 'status-agreed'
				case '拒绝':
				case '已拒绝':
				case '驳回':
					return 'status-rejected'
				case '待处理':
					return 'status-pending'
				default:
					return 'status-default'
			}
		},
		
		// 操作类型选择
		onOperationTypeChange(e) {
			this.operationTypeIndex = e.detail.value
			this.filterApplications()
		},
		
		// 开始日期选择
		onStartDateChange(e) {
			this.startDate = e.detail.value
			this.filterApplications()
		},
		
		// 结束日期选择
		onEndDateChange(e) {
			this.endDate = e.detail.value
			this.filterApplications()
		},
		
		// 搜索输入
		onSearchInput() {
			this.filterApplications()
		},
		
		// 过滤申请记录
		filterApplications() {
			let filtered = [...this.applications]
			
			// 按操作类型过滤
			if (this.operationTypeIndex > 0) {
				const selectedType = this.operationTypes[this.operationTypeIndex]
				filtered = filtered.filter(item => {
					switch (selectedType) {
						case '同意':
							return item.status === '同意' || item.status === '已同意'
						case '驳回':
							return item.status === '拒绝' || item.status === '已拒绝' || item.status === '驳回'
						case '待处理':
							return item.status === '待处理'
						default:
							return true
					}
				})
			}
			
			// 按关键词搜索
			if (this.searchKeyword.trim()) {
				const keyword = this.searchKeyword.trim().toLowerCase()
				filtered = filtered.filter(item => 
					item.agencyName.toLowerCase().includes(keyword) ||
					item.sourceCity.toLowerCase().includes(keyword) ||
					item.operator.toLowerCase().includes(keyword)
				)
			}
			
			// 按日期范围过滤
			if (this.startDate) {
				filtered = filtered.filter(item => {
					const itemDate = new Date(item.applyTime)
					const startDate = new Date(this.startDate)
					return itemDate >= startDate
				})
			}
			
			if (this.endDate) {
				filtered = filtered.filter(item => {
					const itemDate = new Date(item.applyTime)
					const endDate = new Date(this.endDate)
					return itemDate <= endDate
				})
			}
			
			this.filteredApplications = filtered
		},
		
		// 查看申请详情
		viewApplicationDetail(application) {
			uni.navigateTo({
				url: `/public/cooperation/reply-application?applicationId=${application.relationId}&date=${encodeURIComponent('申请记录')}`
			})
		}
	}
}
</script>

<style lang="scss" scoped>
	// 全局变量定义
	$primary-color: #3FBDA3; // 主题绿，贴近设计稿
	$secondary-color: #82A0F7;
	$danger-color: #FF3B30;
	$warning-color: #FC642F;
	$success-color: #4CAF50;
	$gray-color: #8E8E93;
	$light-gray: #F1F1F1;
	$border-color: #EEEEEE;
	$text-primary: #333333;
	$text-secondary: #999999;
	$text-light: #FFFFFF;
	$radius-base: 12rpx;
	$radius-large: 20rpx;
	$shadow-sm: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
	$shadow-md: 0rpx -4rpx 14rpx 0rpx rgba(241, 241, 241, 0.5);
	$transition-base: all 0.3s ease;

	.application-record-container {
		position: relative;
		padding-bottom: 180rpx;
	}

	/* 顶部背景 */
	.page-top-bg {
		position: fixed;
		top: 0;
		left: 0;
		width: 750rpx;
		height: 280rpx;
		background: #57BE9C;
		box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(216,216,216,0.72);
		backdrop-filter: blur(0px);
		pointer-events: none; // 不拦截点击
	}

	/* 内容区域 */
	.content-area {
		background: #eeeeee;
	}

	.main-top-period{
		margin: 24rpx;
		padding: 28rpx 28rpx 12rpx 28rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
	}

	// 产品信息卡片包装器
	.product-card-wrapper {
		padding: 5rpx;
	}

	// 通用区块样式
	.section {
		background:#ffffff;
		margin:24rpx;
		border-radius: 20rpx;

		&-header {
			display: flex;
			align-items: center;
			padding:28rpx;

			&__left {
				display: flex;
				align-items: center;
			}

			&__icon {
				width: 30rpx;
				height: 30rpx;
				margin-right: 20rpx;
				font-size: 28rpx;
				color: $primary-color;
				display: flex;
				align-items: center;
				justify-content: center;
				background: #eeeeee;
			}

			&__title {
				font-size: 28rpx;
				font-weight: 600;
				color: $text-primary;
			}
		}
	}

	// 筛选内容区域
	.filter-content {
		padding: 0 28rpx 28rpx;
	}

	.filter-row {
		display: flex;
		gap: 16rpx;
		margin-bottom: 16rpx;
		align-items: center;
		justify-content: space-between;
	}

	.picker-item {
		background: #f5f5f5;
		border-radius: 8rpx;
		padding: 16rpx 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex: 0 0 calc(50% - 8rpx); // 固定宽度：50% 减去一半的 gap
		min-height: 64rpx;
		box-sizing: border-box;
	}

	.picker-text {
		font-size: 24rpx;
		color: #333;
		line-height: 1.5;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-right: 8rpx;
	}

	.picker-arrow {
		font-size: 20rpx;
		color: #999;
		flex-shrink: 0;
	}

	.search-input-wrapper {
		flex: 0 0 calc(50% - 8rpx); // 固定宽度：50% 减去一半的 gap
		position: relative;
		display: flex;
		align-items: center;
		background: #f5f5f5;
		border-radius: 8rpx;
		min-height: 64rpx;
		box-sizing: border-box;
	}

	.search-input {
		flex: 1;
		background: transparent;
		border: none;
		border-radius: 8rpx;
		padding: 16rpx 20rpx 16rpx 20rpx;
		font-size: 24rpx;
		color: #333;
		line-height: 1.5;
		box-sizing: border-box;
	}

	.search-icon {
		font-size: 28rpx;
		color: #999;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.date-row {
		display: flex;
		gap: 16rpx;
		align-items: center;
		justify-content: space-between;
	}

	.date-picker {
		background: #f5f5f5;
		border-radius: 8rpx;
		padding: 16rpx 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex: 0 0 calc(50% - 8rpx); // 固定宽度：50% 减去一半的 gap
		min-height: 64rpx;
		box-sizing: border-box;
		flex:1;
	}

	.date-text {
		font-size: 24rpx;
		color: #333;
		line-height: 1.5;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-right: 8rpx;
	}

	.date-arrow {
		font-size: 20rpx;
		color: #999;
		flex-shrink: 0;
	}

	// 申请记录列表
	.application-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
		padding: 0 28rpx 28rpx;
	}

	.application-card {
		background: white;
		border: 2rpx solid #39B54A;
		border-radius: 16rpx;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		gap: 30rpx;
	}

	.card-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.group-badge {
		width: 52px;
		background-color: #39B54A1A;
		color: #39B54A;
		border: 1rpx solid #39B54A;
		border-radius: 15rpx;
		padding: 6rpx 0;
		font-size: 24rpx;
		text-align: center;
		box-sizing: border-box;
		margin-right: 15rpx;
	}

	.agency-info {
		display: flex;
		align-items: center;
	}

	.agency-name {
		font-size: 28rpx;
		color: #333333;
		font-weight: 600;
		margin-right: 8rpx;
	}

	.play-icon {
		font-size: 16rpx;
		color: #333333;
	}

	.rating {
		display: flex;
		align-items: center;
	}

	.star-icon {
		font-size: 24rpx;
		color: #FFD700;
		margin-right: 4rpx;
	}

	.rating-value {
		font-size: 24rpx;
		color: #FFD700;
	}

	.card-detail-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.detail-label {
		font-size: 24rpx;
		color: #999999;
		margin-right: 28rpx;
		margin-left: 10rpx;
	}

	.detail-value {
		font-size: 24rpx;
		color: #333333;
	}

	.card-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 16rpx;
		border-top: 1rpx solid #f0f0f0;
	}

	.time-info {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.time-label {
		font-size: 22rpx;
		color: #666;
	}

	.status {
		font-size: 22rpx;
		font-weight: 600;
	}

	.status-agreed {
		color: #999;
	}

	.status-rejected {
		color: #ff3b30;
	}

	.status-pending {
		color: #ff9500;
	}

	.status-default {
		color: #666;
	}

	.operator-info {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.operator-label {
		font-size: 22rpx;
		color: #999;
	}

	.operator-name {
		font-size: 22rpx;
		color: #333;
	}

	.empty-state {
		padding: 40rpx;
		text-align: center;
	}

	.empty-text {
		font-size: 28rpx;
		color: $text-secondary;
	}

	/* 底部操作栏 */
	.bottom-action-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: white;
		border-top: 1rpx solid #E5E5E5;
		padding: 20rpx 24rpx;
		display: flex;
		gap: 16rpx;
		z-index: 100;
	}

	.action-button {
		flex: 1;
		background: white;
		border: 1rpx solid #D9D9D9;
		border-radius: 100rpx;
		padding: 16rpx 0;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.button-text {
		font-size: 28rpx;
		color: #333333;
		font-weight: 600;
	}

	.section-header__title{
		font-size: 28rpx;
		font-weight: 700;
		color: #333333;
	}

	.section-header__icon{
		color:#000000;
	}
</style>
